package com.siashan.toolkit.sms.huaweicloud;

import com.siashan.toolkit.sms.cache.SmsCacheAutoConfiguration;
import com.siashan.toolkit.sms.cache.SmsCacheTemplate;
import com.siashan.toolkit.sms.core.entity.SmsFrequencyLimitConfig;
import com.siashan.toolkit.sms.core.entity.SmsTemplate;
import com.siashan.toolkit.sms.core.entity.SmsWhiteList;
import com.siashan.toolkit.sms.core.utils.SmsTemplateUtils;
import com.siashan.toolkit.sms.huaweicloud.core.HuaWeiCloudSmsConfig;
import com.siashan.toolkit.sms.huaweicloud.core.HuaWeiCloudSmsSendExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.List;
import java.util.Map;

/**
 * 华为云发送端点自动配置
 *
 * @author siashan
 * @since v1.0.1
 */
@Configuration
@EnableConfigurationProperties(HuaWeiCloudSmsProperties.class)
@Import(SmsCacheAutoConfiguration.class)
public class HuaWeiCloudSmsAutoConfiguration {


    @Autowired
    private HuaWeiCloudSmsProperties huaWeiCloudSmsProperties;

    @Autowired
    private SmsCacheTemplate smsCacheTemplate;

    /**
     * 构造华为云发送处理
     *
     * @return 华为云发送处理
     */
    @Bean
    @ConditionalOnMissingBean
    public HuaWeiCloudSmsSendExecutor huaWeiCloudSmsSendExecutor() {
        List<SmsTemplate> templateList = huaWeiCloudSmsProperties.getTmpls();
        Map<String, SmsTemplate> templateMap = SmsTemplateUtils.transMap(templateList);
        HuaWeiCloudSmsConfig config = huaWeiCloudSmsProperties.getConfig();
        SmsWhiteList whiteList = huaWeiCloudSmsProperties.getWhiteList();
        SmsFrequencyLimitConfig frequencyLimit = huaWeiCloudSmsProperties.getFrequencyLimit();
        HuaWeiCloudSmsSendExecutor executor = new HuaWeiCloudSmsSendExecutor(config,templateMap, whiteList,frequencyLimit);
        return executor;
    }

    /**
     * 构造华为云发送模板类
     *
     * @return 华为云发送模板类
     */
    @Bean
    @ConditionalOnMissingBean
    public HuaweiCloudSmsTemplate huaweiCloudSmsTemplate() {
        HuaweiCloudSmsTemplate huaweiCloudSmsTemplate = new HuaweiCloudSmsTemplate(smsCacheTemplate,huaWeiCloudSmsSendExecutor());
        return huaweiCloudSmsTemplate;
    }

}
